package com.desire.service.purchase.impl;

import com.desire.bean.purchase.Apply;
import com.desire.bean.purchase.ApplyDetail;
import com.desire.common.Base.BaseServiceImpl;
import com.desire.mapper.purchase.ApplyDetailMapper;
import com.desire.mapper.purchase.ApplyMapper;
import com.desire.service.purchase.ApplyService;
import com.desire.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author LittleDesire
 * @description
 * @date 2022-05-21 周六 11:18
 * @since 17
 */
@Service
public class ApplyServiceImpl extends BaseServiceImpl<Apply, ApplyMapper> implements ApplyService {
    @Autowired
    ApplyDetailMapper applyDetailMapper;
    private final String APPLY_PREFIX = "cgsq";

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int save(Apply mapOrEntity) {
        // 生成采购申请id
        String id = UUID.randomUUID().toString();
        mapOrEntity.setId(id);
        // 生成采购申请单编号
        mapOrEntity.setCode(generateApplyCode(mapOrEntity.getEuid()));
        int rs = super.save(mapOrEntity);
        if (rs == 1) {
            // 保存采购明细
            List<ApplyDetail> detail = mapOrEntity.getDetail();
            if (null != detail && detail.size() > 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("detail", detail);
                map.put("purchaseId", id);
                rs = applyDetailMapper.saveApplyDetail(map);
            }
        }
        return rs;
    }

    /**
     * 生成采购申请单号  按年归零
     *
     * @param euid 所属企业用户id
     * @return 最新的申请单编号
     */
    String generateApplyCode(String euid) {
        // 查询当前企业用户， 当年最大的编号
        String year = DateUtils.getYear();
        String code = mapper.queryMaxCode(euid, year);
        if (null == code) {
            // 是当前年的第一个申请单编号
            return APPLY_PREFIX + year + "0001";
        }
        // 在最大的申请单编号处理后加1获得新的申请单编号
        return getNextCode(code);
    }

    /**
     * 获得当前最大编号的下一个编号
     *
     * @param code
     * @return
     */
    String getNextCode(String code) {
        String pre = code.substring(0, 8);
        String seq = code.substring(8);
        int i = Integer.parseInt(seq);
        i++;
        return pre + String.format("%04d", i);
    }

}
